{% extends "teacher/base.html" %}

{% block title %}成绩分布分析 - 期末成绩登记统计分析系统{% endblock %}

{% block content %}
<div class="card mt-4">
  <div class="card-title">
    <i class="fas fa-chart-pie"></i>
    成绩分布分析
    <div class="float-end">
      <select id="semesterSelect" class="form-select form-select-sm d-inline-block w-auto me-2">
        <option value="">全部学期</option>
      </select>
      <button class="btn btn-sm btn-outline-primary" onclick="toggleView()">
        <i class="fas fa-exchange-alt"></i> 切换视图
      </button>
    </div>
  </div>
  <div id="chartView" class="chart-container" style="position: relative; height:400px !important;">
    <canvas id="distributionChart"></canvas>
  </div>
  <div id="tableView" class="table-container" style="display: none;">
    <div class="table-responsive">
      <table class="table table-striped table-hover">
        <thead>
          <tr>
            <th class="text-center" style="width: 20%">分数段</th>
            <th class="text-center" style="width: 20%">人数</th>
            <th class="text-center" style="width: 20%">占比</th>
            <th class="text-center" style="width: 40%">分布图</th>
          </tr>
        </thead>
        <tbody id="distributionTableBody">
        </tbody>
      </table>
    </div>
  </div>
  <div class="distribution-note mt-3">
    <p class="text-muted">
      <i class="fas fa-info-circle"></i>
      成绩分布反映了班级整体学习情况，可以帮助教师了解教学效果和学生的学习状况。
    </p>
  </div>
</div>
{% endblock %}

{% block styles %}
{{ super() }}
<link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
<style>
  .chart-container {
    margin-top: 20px;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }

  .table-container {
    margin-top: 20px;
    background: white;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }

  .table-responsive {
    margin: 0;
    padding: 0;
    border-radius: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    width: 100%;
  }

  .table {
    margin-bottom: 0;
    border-collapse: separate;
    border-spacing: 0;
    width: 100%;
  }

  .table th {
    background-color: #f8f9fa;
    color: #2c3e50;
    font-weight: 600;
    border-bottom: 2px solid #dee2e6;
    padding: 12px;
    white-space: nowrap;
  }

  .table td {
    vertical-align: middle;
    color: #495057;
    padding: 12px;
    border-bottom: 1px solid #dee2e6;
  }

  .table tbody tr:hover {
    background-color: rgba(118, 75, 162, 0.05);
  }

  .card {
    border: none;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border-radius: 15px;
  }

  .card-title {
    padding: 20px;
    background: #e9eef4;
    color: #2c3e50;
    border-radius: 15px 15px 0 0;
    font-size: 1.2em;
  }

  .btn-outline-primary {
    color: #2c3e50;
    padding: .45rem .50rem;
    font-size: .875rem;
    background-color: transparent;
    border-width: 1px;
    border-radius: 0.25rem;
    transition: all 0.3s ease;
  }

  .btn-outline-primary:hover {
    color: #764ba2;
    background-color: white;
    border-color: #764ba2;
  }

  .main-content {
    margin-top: 70px !important;
  }

  .form-select {
    border-color: #2c3e50;
    color: #2c3e50;
    font-size: .875rem;
    padding: .45rem 2rem .45rem .75rem;
    border-radius: 0.25rem;
    transition: all 0.3s ease;
    background-color: white;
    cursor: pointer;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%232c3e50' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right 0.75rem center;
    background-size: 16px 12px;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
  }

  .form-select:focus {
    border-color: #764ba2;
    box-shadow: 0 0 0 0.2rem rgba(118, 75, 162, 0.25);
  }

  .form-select:hover {
    border-color: #764ba2;
  }

  .form-select option {
    padding: 8px;
  }

  .form-select option:hover {
    background-color: #f8f9fa;
  }

  /* 调整页面布局以避免被导航栏遮挡 */
  .container-fluid {
    padding-top: 20px;
  }

  .main-content {
    padding-top: 20px;
  }

  .float-end {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-left: auto;
  }

  .progress {
    height: 20px;
    background-color: #e9ecef;
    border-radius: 4px;
    overflow: hidden;
  }

  .progress-bar {
    background-color: #257dd4;
    transition: width 0.6s ease;
    color: white;
    font-weight: 500;
  }

  .distribution-note {
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
    font-size: 0.9em;
    margin: 20px;
  }

  .distribution-note i {
    color: #6c757d;
    margin-right: 5px;
  }
</style>
{% endblock %}

{% block scripts %}
{{ super() }}

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<script>
  let chart = null;
  let distributionData = null;
  let semesters = [];
  let currentView = 'chart';

  // 检查Chart.js是否加载成功
  function checkChartJsLoaded() {
    if (typeof Chart === 'undefined') {
      console.error('Chart.js 未加载成功');
      alert('图表库加载失败，请刷新页面重试');
      return false;
    }
    return true;
  }

  function toggleView(event) {
    if (event) {
      event.stopPropagation();
      event.preventDefault();
    }
    const chartView = document.getElementById('chartView');
    const tableView = document.getElementById('tableView');

    if (currentView === 'chart') {
      chartView.style.display = 'none';
      tableView.style.display = 'block';
      currentView = 'table';
      updateTable();
    } else {
      chartView.style.display = 'block';
      tableView.style.display = 'none';
      currentView = 'chart';
    }
  }

  function updateTable() {
    if (!distributionData) return;

    const tbody = document.getElementById('distributionTableBody');
    tbody.innerHTML = '';

    const total = distributionData.values.reduce((a, b) => a + b, 0);
    distributionData.labels.forEach((label, index) => {
      const value = distributionData.values[index];
      const percentage = ((value / total) * 100).toFixed(1);
      const barWidth = percentage + '%';

      const row = document.createElement('tr');
      row.innerHTML = `
        <td class="text-center">${label}</td>
        <td class="text-center">${value}</td>
        <td class="text-center">${percentage}%</td>
        <td>
          <div class="progress" style="height: 20px;">
            <div class="progress-bar" role="progressbar" style="width: ${barWidth};" 
                 aria-valuenow="${percentage}" aria-valuemin="0" aria-valuemax="100">
              ${barWidth}
            </div>
          </div>
        </td>
      `;
      tbody.appendChild(row);
    });
  }

  function createChart(ctx) {
    if (!checkChartJsLoaded()) return;

    if (chart) {
      chart.destroy();
    }

    try {
      chart = new Chart(ctx, {
        type: 'pie',
        data: {
          labels: distributionData.labels,
          datasets: [{
            data: distributionData.values,
            backgroundColor: [
              'rgba(255, 99, 132, 0.8)',
              'rgba(255, 159, 64, 0.8)',
              'rgba(255, 205, 86, 0.8)',
              'rgba(75, 192, 192, 0.8)',
              'rgba(54, 162, 235, 0.8)'
            ],
            borderColor: [
              'rgb(255, 99, 132)',
              'rgb(255, 159, 64)',
              'rgb(255, 205, 86)',
              'rgb(75, 192, 192)',
              'rgb(54, 162, 235)'
            ],
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            title: {
              display: true,
              text: '成绩分布',
              font: {
                size: 18,
                weight: 'bold'
              },
              padding: {
                top: 10,
                bottom: 20
              }
            },
            tooltip: {
              callbacks: {
                label: function (context) {
                  const label = context.label || '';
                  const value = context.raw;
                  const total = context.dataset.data.reduce((a, b) => a + b, 0);
                  const percentage = ((value / total) * 100).toFixed(1);
                  return `${label}: ${value}人 (${percentage}%)`;
                }
              }
            },
            legend: {
              position: 'right',
              labels: {
                usePointStyle: true,
                padding: 20,
                font: {
                  size: 12
                }
              }
            }
          }
        }
      });
    } catch (error) {
      console.error('创建图表失败:', error);
      alert('创建图表失败，请刷新页面重试');
    }
  }

  function loadData(semester = '') {
    const url = semester ? `/teacher/analysis/data?semester=${semester}` : '/teacher/analysis/data';

    // 显示加载状态
    const chartView = document.getElementById('chartView');
    const tableView = document.getElementById('tableView');
    if (currentView === 'chart') {
      chartView.innerHTML = '<div class="text-center p-5"><i class="fas fa-spinner fa-spin"></i> 加载中...</div>';
    } else {
      tableView.innerHTML = '<div class="text-center p-5"><i class="fas fa-spinner fa-spin"></i> 加载中...</div>';
    }

    fetch(url)
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then(result => {
        if (result.success) {
          distributionData = result.data.distribution;
          semesters = result.data.semesters;

          // 更新学期选择器，倒序显示
          const semesterSelect = document.getElementById('semesterSelect');
          semesterSelect.innerHTML = '<option value="">全部学期</option>';
          semesters.slice().reverse().forEach(semester => {
            semesterSelect.innerHTML += `<option value="${semester}">${semester}</option>`;
          });
          if (semester) {
            semesterSelect.value = semester;
          }

          // 恢复图表容器
          chartView.innerHTML = '<canvas id="distributionChart"></canvas>';
          tableView.innerHTML = `
            <div class="table-responsive">
              <table class="table table-striped table-hover">
                <thead>
                  <tr>
                    <th class="text-center" style="width: 20%">分数段</th>
                    <th class="text-center" style="width: 20%">人数</th>
                    <th class="text-center" style="width: 20%">占比</th>
                    <th class="text-center" style="width: 40%">分布图</th>
                  </tr>
                </thead>
                <tbody id="distributionTableBody"></tbody>
              </table>
            </div>
          `;

          // 创建图表
          const ctx = document.getElementById('distributionChart').getContext('2d');
          createChart(ctx);

          // 如果当前是表格视图，更新表格
          if (currentView === 'table') {
            updateTable();
          }
        } else {
          throw new Error(result.message || '获取数据失败');
        }
      })
      .catch(error => {
        console.error('Error:', error);
        const errorMessage = error.message || '获取数据失败，请稍后重试';
        if (currentView === 'chart') {
          chartView.innerHTML = `<div class="text-center p-5 text-danger"><i class="fas fa-exclamation-circle"></i> ${errorMessage}</div>`;
        } else {
          tableView.innerHTML = `<div class="text-center p-5 text-danger"><i class="fas fa-exclamation-circle"></i> ${errorMessage}</div>`;
        }
      });
  }

  // 等待DOM和Chart.js都加载完成
  window.addEventListener('load', function () {
    if (checkChartJsLoaded()) {
      loadData();

      // 监听学期选择变化
      document.getElementById('semesterSelect').addEventListener('change', function () {
        loadData(this.value);
      });
    }
  });
</script>
{% endblock %}